import { Dispatch } from "redux";
import { MyAxios, IResBody } from "../../../../common/config/http";
import { IReducerState_TableFilter, IReducerState_Form } from "./reducer";
import * as Types from "./types";
import { IAction } from "../../../../common/store/actions";
import { IForm } from "../form/add/interface";

// 获取table列表
export function getTableDatasourceAct(filter: IReducerState_TableFilter) {
  const data = {
    pageNum: filter.pageNum,
    pageSize: filter.pageSize,
    orderByClause: filter.sortColumn
      ? `${filter.sortColumn} ${filter.sortType}`
      : null,
    keyWords: filter.keyWords ? filter.keyWords : null
  };
  return (dispatch: Dispatch) => {
    // get data
    dispatch({ type: Types.TABLE.LOADING, data: true });
    MyAxios.axios
      .post("area/all", data, {
        headers: { ...MyAxios.getToken() }
      })
      .then(res => {
        const data = res.data;
        const action: IAction = { type: Types.TABLE.DATASOURCE, data: data };
        dispatch(action);
      })
      .catch(e => {})
      .finally(() => {
        dispatch({ type: Types.TABLE.LOADING, data: false });
      });
  };
}

// 修改table的过滤参数
export function setTableFilterAct(filter: IReducerState_TableFilter): IAction {
  getTableDatasourceAct(filter);
  return { type: Types.TABLE.FILTER, data: filter };
}

// 展示添加表单
export function formShow_addAct(formInfo: IReducerState_Form): IAction {
  return { type: Types.FORM, data: { ...formInfo, visible_add: true } };
}

// 隐藏添加表单
export function formHide_addAct(formInfo: IReducerState_Form): IAction {
  return { type: Types.FORM, data: { ...formInfo, visible_add: false } };
}

// 提交表单-添加
export function formSubmit_addAct(
  data: any,
  callback: (res: IResBody) => void
) {
  return (dispatch: Dispatch) => {
    MyAxios.axios
      .post<any, IResBody>("area", data, {
        headers: { ...MyAxios.getToken() }
      })
      .then(res => {
        callback(res);
      });
  };
}

// 展示修改表单
export function formShow_editAct(id: number, formInfo: IReducerState_Form) {
  return (dispatch: Dispatch) => {
    MyAxios.axios
      .get<any, IResBody>(`area/${id}`, { headers: { ...MyAxios.getToken() } })
      .then(res => {
        console.log(res);
        const action: IAction = {
          type: Types.FORM,
          data: { ...formInfo, echo_edit: res.data, visible_edit: true }
        };
        dispatch(action);
      });
  };
}

export function formSubmit_editAct(
  data: any,
  callback: (res: IResBody) => void
) {
  return (dispatch: Dispatch) => {
    MyAxios.axios
      .put<any, IResBody>("area",data, { headers: { ...MyAxios.getToken() } })
      .then(res => {
        console.log(res);
        callback(res);
      });
  };
}

// 隐藏修改表单
export function formHide_editAct(formInfo: IReducerState_Form): IAction {
  return {
    type: Types.FORM,
    data: { ...formInfo, visible_edit: false, echo_edit: null }
  };
}
